package com.may.wind.service;

import com.may.wind.dao.UserRoleRepository;
import com.may.wind.entity.Role;
import com.may.wind.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserRoleService {
    @Autowired
    UserRoleRepository userRoleRepository;

    public List<UserRole> getAllByUserId(long userId) {
        return userRoleRepository.findAllByUserId(userId);
    }

    @Transactional
    public void saveRoleChanges(long userId, List<Role> roles) {
        userRoleRepository.deleteAllByUserId(userId);
        List<UserRole> userRoles = new ArrayList<>();
        roles.forEach(role -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRolesId(role.getId());
            userRoles.add(userRole);
        });
        userRoleRepository.saveAll(userRoles);
    }
}
